#!/usr/bin/env python
import sys, pygame
from menu_lib import cMenu,EVENT_CHANGE_STATE

from settingsbuilder import SettingsBuilder
from maploader import TileMapLoader
from game import NoNetGame,ServerGame,ClientGame
from common import load_image

PROGNAME = 'Turb'
PROFILE = False
map_loader = TileMapLoader(r'./Maps')

def start_game(settings):
    game = NoNetGame(map_loader)
    game.startGame(settings)
settings = None

def main():
    global settings
    log = sys.stderr

    log.write("Parsing Settings ini file and command line\n")
    settings = SettingsBuilder(map_loader).getSettings()
    widescreen = False
    aspect_ratio = (16.0/10.0) if widescreen else 4/3.0
    width = 640
    height = width/aspect_ratio
    print "Resolution",(width, height)

    # Create a window of 800x600 pixels
    flags = 0
    if settings['graphics']['fullscreen']:
        flags = flags | pygame.FULLSCREEN 
    screen = pygame.display.set_mode((width, height),flags)
    pygame.font.init()
    pygame.mouse.set_visible(0)
    pygame.display.set_caption('menu')
    # fix the sound delay issue on ubuntu (Pulse Audio)
    pygame.mixer.pre_init(44100, -16, 2, 512*2)
    pygame.mixer.init()    
    # Ignore mouse motion (greatly reduces resources when not needed)
    pygame.event.set_blocked(pygame.MOUSEMOTION)
    
    # Create 3 diffrent menus.  One of them is only text, another one is only
    # images, and a third is -gasp- a mix of images and text buttons!  To
    # understand the input factors, see the menu file
    menu = cMenu(50, 50, 20, 5, 'vertical', 100, screen,
                    [('Start 1 Player Game', 1, None),
                     ('Start 2 Player Game',  2, None),
                     ('Toggle Full Screen',     3, None),
                     ('Exit',         4, None)])

    # Center the menu on the draw_surface (the entire screen here)
    menu.set_center(True, True)

    # Center the menu on the draw_surface (the entire screen here)
    menu.set_alignment('center', 'center')

    # Create the state variables (make them different so that the user event is
    # triggered at the start of the "while 1" loop so that the initial display
    # does not wait for user input)
    state = 0
    prev_state = 1

    # rect_list is the list of pygame.Rect's that will tell pygame where to
    # update the screen (there is no point in updating the entire screen if only
    # a small portion of it changed!)
    rect_list = []
    # Ignore mouse motion (greatly reduces resources when not needed)
    pygame.event.set_blocked(pygame.MOUSEMOTION)

    # background
    bkg = load_image('data/bmp/bkg.jpg')
    screen.blit(bkg, (0, 0))
    pygame.display.flip()

    # The main while loop
    while 1:
        # Check if the state has changed, if it has, then post a user event to
        # the queue to force the menu to be shown at least once
        if prev_state != state:
            pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key = 0))
            prev_state = state


        # Get the next event
        e = pygame.event.wait()

        # Update the menu, based on which "state" we are in - When using the menu
        # in a more complex program, definitely make the states global variables
        # so that you can refer to them by a name
        if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE: #@IndentOk
            if state == 0:
                rect_list, state = menu.update(e, state)
            elif state == 1:
                print 'Start Game!'
                settings['game']['no_of_players'] = 1
                if PROFILE:
                    import cProfile
                    cProfile.run('start_game(settings)')
                else:
                    start_game(settings)
                screen.blit(bkg, (0, 0))
                pygame.display.flip()
                state = 0
            elif state == 2:
                game = NoNetGame(map_loader)
                settings['game']['no_of_players'] = 2
                start_game(settings)
                state = 0
            elif state == 3:
                settings['graphics']['fullscreen'] = not settings['graphics']['fullscreen']
                flags = 0
                if settings['graphics']['fullscreen']:
                    flags = flags | pygame.FULLSCREEN
                else: 
                    flags = flags & ~pygame.FULLSCREEN
                pygame.display.set_mode((width, height),flags)
                print 'Options!'
                state = 0
            else:
                print 'Exit!'
                pygame.quit()
                sys.exit()

        # Quit if the user presses the exit button
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # Update the screen
        pygame.display.update(rect_list)


if __name__ == "__main__":
    main()

